package ccot.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class ExamServlet
 */
@WebServlet("/ExamServlet")
public class ExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private DataSource dataSource;
    private Connection connection;
    private Statement statement;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init() throws ServletException {
        try {
            Context initContext  = new InitialContext();
            dataSource = (DataSource)initContext.lookup("java:comp/env/jdbc/ccot");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
    
    private boolean createExam(
    	String name, 
    	int duration, 
    	String description 
    ) {
    	boolean success = false;
    	
    	ResultSet resultSet = null;
    	try {
    		connection = dataSource.getConnection();
    		statement = connection.createStatement();
    		String query = "SELECT * FROM exams WHERE name='" + name + "'";
    		resultSet = statement.executeQuery(query);
    		if (resultSet.next()) {
    			success = false;
    			return success;
    		}
    		
    		String sql = "INSERT INTO exams (name, duration, description) VALUES('" 
    				+ name + "','" 
    				+ duration + "','"
    				+ description + "')";
    		System.out.println(sql);
    		statement.executeUpdate(sql);
    		success = true;
    	} catch (SQLException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (null != statement) {
    				statement.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		try {
    			if (null != connection) {
    				connection.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    	
    	return success;
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	
    	String action = request.getParameter("action");
    	if (action.equals("create")) {
    		String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
    		int duration = Integer.parseInt(request.getParameter("duration"));
        	String description = new String(request.getParameter("description").getBytes("ISO-8859-1"), "UTF-8");
        	
        	boolean success = createExam(name, duration, description);
        	if (success) {
        		out.println("<p>已创建考试科目：" + name + "</p>");
        	} else {
        		out.println("<p>无法创建考试科目，该考试科目或许已经存在！</p>");
        	}
    	}
    	
    	
    	ResultSet resultSet = null;
    	try {
    		connection = dataSource.getConnection();
    		statement = connection.createStatement();
    		String query = "select * from exams limit 10";
    		resultSet = statement.executeQuery(query);
    		if (resultSet.next()) {
    			String name = resultSet.getString("name");
    			String duration = resultSet.getString("duration");
    			String description = resultSet.getString("description");
    			out.println("<p>" + name + ", " + duration + ", " + description + "</p>");
    		} else {
    			System.out.println("nothing");
    			out.println("nothing");
    		}
    	} catch (SQLException e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (null != resultSet) {
    				resultSet.close();
    			}
    		} catch (SQLException e) {
				e.printStackTrace();
			}
    		try {
    			if (null != statement) {
    				statement.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		try {
    			if (null != connection) {
    				connection.close();
    			}
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    	}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		processRequest(request, response);
	}

}
